package com.traffic.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.traffic.constant.Status;
import com.traffic.entity.*;
import com.traffic.exception.BaseException;
import com.traffic.model.ApiResponse;
import com.traffic.service.AdminService;
import com.traffic.service.AuthService;
import com.traffic.service.UserInfoService;
import com.traffic.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/8
 */
@Api(tags = "管理员相关接口")
@RequestMapping(value = "/admin")
@RestController
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private AuthService authService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "【管理员注册】", notes = "参数账号密码")
    @PostMapping(value = "/register")
    public ApiResponse register(@RequestParam("account") String account, @RequestParam("password") String password) {
        Admin admin = adminService.register(account, password);
        if (ObjectUtil.isNotNull(admin)) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【权限管理-添加新用户】", notes = "参数:account password phone role")
    @PostMapping(value = "/register/new")
    public ApiResponse registerAdmin(@RequestBody Map<String,Object> param) {
        String account = param.get("name").toString();
        String password = param.get("password").toString();
        String phone = param.get("phone").toString();
        Long role = Long.parseLong(param.get("role").toString());

        Admin admin = adminService.register(account, password, phone, role);
        if (ObjectUtil.isNotNull(admin)) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【修改管理员信息】")
    @PostMapping(value = "/edit")
    public ApiResponse edit(@RequestBody Map<String, Object> param) {
        Long id = Long.parseLong(param.get("id").toString());
        String name = param.get("name").toString();
        String password = param.get("password").toString();
        String phone = param.get("phone").toString();
        Integer status = Integer.parseInt(param.get("status").toString());
        Long role = Long.parseLong(param.get("role").toString());

        Integer result = adminService.editAdmin(id, name, phone, role, status, password);
        if (result > 0) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【管理员登录】", notes = "参数账号密码")
    @GetMapping(value = "/login")
    public ApiResponse login(@RequestParam("account") String account, @RequestParam("password") String password) {
        String token = adminService.login(account, password);
        if (StrUtil.isNotEmpty(token)) {
            return ApiResponse.ofStatus(Status.OK, token);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【高级管理员直接修改管理员信息】", notes = "最高权限管理员Token")
    @PutMapping(value = "/direct/edit")
    public ApiResponse directEditAdmin(@RequestBody Map<String, Object> adminParam) {
        String param[] = new String[] {"id", "password", "name", "phone", "account"};
        List<String> paramList = CollUtil.newArrayList(param);
        if (!paramList.containsAll(CollUtil.newArrayList(adminParam.keySet().toArray()))) {
            throw new BaseException(Status.PARAM_ERROR);
        }
        Admin old = adminService.getById(adminParam.get("id").toString());
        if (ObjectUtil.isNotNull(old)) {
            BeanUtil.copyProperties(adminParam, old, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            // 其中密码要特殊处理
            if (adminParam.containsKey("password")) {
                old.setPassword(SecureUtil.md5(old.getSalt() + adminParam.get("password").toString().trim()));
            }
            Admin admin = adminService.editAdminInfo(old);
            return ApiResponse.ofStatus(Status.OK, admin);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【管理员退出登录】", notes = "需要token")
    @GetMapping(value = "/logout")
    public ApiResponse logout() {
        if (adminService.logout()) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【高级管理员删除下一级管理员的账户】", notes = "需要最高管理员token")
    @DeleteMapping(value = "/delete/{adminId}")
    public ApiResponse deleteAdmin(@PathVariable Long adminId) {
        if (adminService.delete(adminId)) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【获取设置的权限列表】")
    @GetMapping(value = "/auth")
    public ApiResponse getAuthList() {
        return ApiResponse.ofStatus(Status.OK, authService.getAuthList());
    }

    @ApiOperation(value = "【new---分页获取设置的权限列表】")
    @GetMapping(value = "/auth/page")
    public ApiResponse getAuthListPages(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryResult result = authService.queryRolesPages(currentPage, pageSize);
        return ApiResponse.ofStatus(Status.OK, result);
    }

    @ApiOperation(value = "【赋予角色权限】",notes = "最高权限管理员Token")
    @PutMapping(value = "/auth/give/{roleId}/{authId}")
    public ApiResponse giveAuth(@PathVariable Long roleId, @PathVariable Long authId) {
        Boolean result = authService.giveAuth(authId, roleId);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.COMMON_ERROR);
        }
    }

    @ApiOperation(value = "【移除角色权限】",notes = "最高权限管理员Token")
    @PutMapping(value = "/auth/remove/{roleId}/{authId}")
    public ApiResponse removeAuth(@PathVariable Long roleId, @PathVariable Long authId) {
        Boolean result = authService.removeAuth(authId, roleId);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.COMMON_ERROR);
        }
    }

    @ApiOperation(value = "【添加一个角色】", notes = "ADMIN权限")
    @PostMapping(value = "/role/{name}")
    public ApiResponse addRole(@PathVariable String name) {
        Role role = authService.addRole(name);
        return ApiResponse.ofStatus(Status.OK, role);
    }

    @ApiOperation(value = "【修改角色的名称】")
    @PutMapping(value = "/role/{roleId}/{name}")
    public ApiResponse editRole(@PathVariable Long roleId, @PathVariable String name) {
        Role role = authService.editRole(name, roleId);
        return ApiResponse.ofStatus(Status.OK, role);
    }

    @ApiOperation(value = "【权限管理-添加新用户-查询角色列表】")
    @GetMapping(value = "/role")
    public ApiResponse queryRoles(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "100") Integer pageSize) {
        List<Role> roles = authService.queryRoles(currentPage, pageSize);
        return ApiResponse.ofStatus(Status.OK, roles);
    }

    @ApiOperation(value = "【单个角色查询】")
    @GetMapping(value = "role/{name}")
    public ApiResponse queryRole(@PathVariable String name) {
        Role role = authService.findRole(name);
        return ApiResponse.ofStatus(Status.OK, role);
    }

    @ApiOperation(value = "【为管理员分配角色】", notes = "最高权限管理员token")
    @PutMapping(value = "/role/set/admin/{adminId}/{roleId}")
    public ApiResponse setAdminRole(@PathVariable Long adminId, @PathVariable Long roleId) {
        Boolean result = authService.setRoleAdmin(adminId, roleId);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.COMMON_ERROR);
        }
    }

    @ApiOperation(value = "【为用户分配角色】", notes = "最高权限管理员token")
    @PutMapping(value = "/role/set/user/{userId}/{roleId}")
    public ApiResponse setUserRole(@PathVariable Long userId, @PathVariable Long roleId) {
        Boolean result = authService.setRoleUser(userId, roleId);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.COMMON_ERROR);
        }
    }

    @ApiOperation(value = "【管理员新建用户】", notes = "拥有ADD权限的管理员token")
    @PostMapping(value = "/add/user")
    public ApiResponse addUser(@RequestBody Map<String, Object> param) {
        User user = userService.createUser(param);
        if (ObjectUtil.isNotNull(user)) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【管理员修改用户信息】", notes = "拥有EDIT权限的管理员token")
    @PutMapping(value = "/edit/user/{userId}")
    public ApiResponse editUserInfo(@PathVariable Long userId, @RequestBody Map<String, Object> infoParams) {
        UserInfo userInfo = userInfoService.getUserInfoByUserId(userId);
        if (ObjectUtil.isNotNull(userInfo)) {
            String param[] = new String[] {"nickName", "city", "birthday", "sex", "profile", "phone"};
            List<String> paramList = CollUtil.newArrayList(param);
            if (!paramList.containsAll(CollUtil.newArrayList(infoParams.keySet().toArray()))) {
                throw new BaseException(Status.PARAM_ERROR);
            }
            // 手机号修改要特殊处理
            if (infoParams.containsKey("phone")) {
                BeanUtil.copyProperties(infoParams, userInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                UserInfo result = userInfoService.editUserInfoIncludePhone(userInfo);
                return ApiResponse.ofStatus(Status.OK, result);
            }else {
                BeanUtil.copyProperties(infoParams, userInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                UserInfo result = userInfoService.editUserInfo(userInfo);
                return ApiResponse.ofStatus(Status.OK, result);
            }
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【管理员删除用户账户】", notes = "拥有DELETE权限的管理员token")
    @DeleteMapping(value = "/delete/user/{userId}")
    public ApiResponse deleteUser(@PathVariable Long userId) {
        if (userInfoService.deleteUser(userId)) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【权限管理-获取管理员列表】", notes = "参数：currentPage pageSize")
    @GetMapping(value = "/list")
    public ApiResponse queryAdmins(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize) {
        return ApiResponse.ofStatus(Status.OK, adminService.queryAdmins(currentPage, pageSize));
    }

    @ApiOperation(value = "【禁用管理员账户】")
    @GetMapping(value = "/ban")
    public ApiResponse banAdmins(@RequestParam List<Long> param) {
        return ApiResponse.ofStatus(Status.OK, adminService.ban(param));
    }

    @ApiOperation(value = "【启用管理员账户】")
    @GetMapping(value = "/pass")
    public ApiResponse passAdmins(@RequestParam List<Long> param) {
        return ApiResponse.ofStatus(Status.OK, adminService.pass(param));
    }

    @ApiOperation(value = "【批量删除管理员账户】")
    @GetMapping(value = "/deletes")
    public ApiResponse deleteAdmins(@RequestParam List<Long> param) {
        return ApiResponse.ofStatus(Status.OK, adminService.deleteList(param));
    }

    @ApiOperation(value = "【通过手机号或者账户查询】")
    @GetMapping(value = "/query/{queryInfo}")
    public ApiResponse query(@PathVariable String queryInfo) {
        return ApiResponse.ofStatus(Status.OK, adminService.query(queryInfo));
    }

    @ApiOperation(value = "【查询管理员账户的信息】")
    @GetMapping(value = "/{id}")
    public ApiResponse getAdmin(@PathVariable Long id) {

        return ApiResponse.ofStatus(Status.OK, adminService.queryById(id));
    }

    @ApiOperation(value = "【角色单个删除】")
    @GetMapping(value = "/role/delete/{id}")
    public ApiResponse deleteRole(@PathVariable Long id) {
        Boolean result = authService.deleteRole(id);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.AUTH_ROLE_HAVE);
    }

    @ApiOperation(value = "【角色批量删除】")
    @GetMapping(value = "/role/deletes")
    public ApiResponse deleteRoles(@RequestParam List<Long> ids) {
        return ApiResponse.ofStatus(Status.OK, authService.deleteRole(ids));
    }

    @ApiOperation(value = "【获取所有role】")
    @GetMapping(value = "/role/getAll")
    public ApiResponse getAllRoles() {
        List<Role> roles = authService.queryRoles(1, 1000);
        return ApiResponse.ofStatus(Status.OK, roles);
    }

    @ApiOperation(value = "【获取设置的权限auth】")
    @GetMapping(value = "/auth/getAll")
    public ApiResponse getAllAuth() {
        List<Auth> auths = authService.getAllAuth();
        return ApiResponse.ofStatus(Status.OK, auths);
    }

    @ApiOperation(value = "【创建角色】")
    @GetMapping("/role/create")
    public ApiResponse createRole(@RequestParam String name, @RequestParam List<Integer> auths) {
        Boolean result = authService.createRole(name, auths);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.COMMON_ERROR);
        }
    }

    @ApiOperation(value = "【修改角色】")
    @GetMapping("/role/edit")
    public ApiResponse createRole(@RequestParam Integer id, @RequestParam String name, @RequestParam List<Integer> auths) {
        Boolean result = authService.editRole(id, name, auths);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }
        return ApiResponse.ofStatus(Status.COMMON_ERROR);
    }

    @ApiOperation(value = "【通过id查询role】")
    @GetMapping("/role/query/{id}")
    public ApiResponse findRole(@PathVariable Integer id) {
        return ApiResponse.ofStatus(Status.OK, authService.queryRoleById(id));
    }

    @ApiOperation(value = "【通过account查询admin】")
    @GetMapping("/account/query/{account}")
    public ApiResponse getAdminByAccount(@PathVariable String account) {
        return ApiResponse.ofStatus(Status.OK, adminService.get(account));
    }

    @ApiOperation(value = "【admin修改自己的信息】")
    @GetMapping("/own/edit")
    public ApiResponse ownEditInfo(@RequestParam Long id, @RequestParam String name, @RequestParam String phone,
                                   @RequestParam String p1, @RequestParam String p2) {
        Boolean result = adminService.ownEditInfo(id, name, phone, p1, p2);
        if (result) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.COMMON_ERROR);
        }
    }
}
